package com.cris.helper;

import com.cris.model.Stuff;
import com.cris.service.StuffService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by owen on 2017/5/15.
 */
public class MyRealm extends AuthorizingRealm {



    //设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("myRealm");
    }

    //用于认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //token是用户输入的
        //第一步:丛token中取出身份信息
        String userCode= (String) token.getPrincipal();
        StuffService stuffService = new StuffService();
        Stuff stuff = stuffService.getStuffByName(userCode);
        if(stuff!=null){
            SimpleAuthenticationInfo simpleAuthenticationInfo=new
                    SimpleAuthenticationInfo(stuff.getName(),stuff.getPassword(),this.getName());
            return simpleAuthenticationInfo;
        }
        else
            return null;

    }
    //用于授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) 	{

        StuffService stuffService = new StuffService();
        String username = (String)principals.getPrimaryPrincipal();
        Stuff stuff = stuffService.getStuffByName(username);
        if (stuff.getRole().equals("user")){
            Set<String> roles = new HashSet<>();
            Set<String> perms = new HashSet<>();
            roles.add("user");
            //添加user需要的权限
            perms.add("product");
            perms.add("sale");
            perms.add("productType");
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.setRoles(roles);
            authorizationInfo.setStringPermissions(perms);
            return authorizationInfo;
        }
        else if (stuff.getRole().equals("admin")){
            Set<String> roles = new HashSet<>();
            Set<String> perms = new HashSet<>();
            roles.add("admin");
            //添加admin需要的权限
            perms.add("product");
            perms.add("sale");
            perms.add("productType");
            perms.add("chart");
            perms.add("register");
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.setRoles(roles);
            authorizationInfo.setStringPermissions(perms);
            return authorizationInfo;
        }
        else return null;

    }


}
